package repository

import (
	"errors"

	"away.wei/minidevpos/db"
	"away.wei/minidevpos/global"
	"away.wei/minidevpos/model"
	"gorm.io/gorm"
)

type ProjectRep struct{}

func (s *ProjectRep) Create(dto db.Project) (db.Project, error) {
	if (!errors.Is(global.DB.First(&db.Project{}, "name = ?", dto.Name).Error, gorm.ErrRecordNotFound)) {
		return dto, errors.New("存在相同的Name，不允许创建")
	}
	db := global.DB.Create(&dto)
	return dto, db.Error
}

func (s *ProjectRep) Delete(ids []int) error {
	return global.DB.Delete(&db.Project{}, "id in ?", ids).Error
}

func (s *ProjectRep) Update(dto db.Project) error {
	return global.DB.Updates(&dto).Error
}

func (s *ProjectRep) Details(id int) (dto db.Project, err error) {
	err = global.DB.First(&dto, id).Error
	return dto, err
}

func (s *ProjectRep) GetPage(dto model.ProjectSearch) (list interface{}, total int64, err error) {
	limit := dto.PageSize
	offset := dto.PageSize * (dto.Page - 1)
	dbquery := global.DB.Model(&db.Project{})
	var dtos []db.Project
	if dto.ID != 0 {
		dbquery = dbquery.Where("`id` = ?", dto.ID)
	}
	if dto.Name != "" {
		dbquery = dbquery.Where("name like ?", "%"+dto.Name+"%")
	}

	err = dbquery.Count(&total).Error
	if err != nil {
		return
	}
	err = dbquery.Limit(limit).Offset(offset).Find(&dtos).Error
	return dtos, total, err
}
